package com.atguigu.daijia.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CiService;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class CosServiceImpl implements CosService {

    private final TencentCloudProperties tencentCloudProperties;
    private final CiService ciService;

    private COSClient getPrivateCOSClient() {
        COSCredentials cosCredentials = new BasicCOSCredentials(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCloudProperties.getRegion()));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        return new COSClient(cosCredentials, clientConfig);
    }

    /**
     * 上传文件
     * @param file
     * @param path
     * @return
     */
    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        COSClient cosClient = this.getPrivateCOSClient();

        // 元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());
        metadata.setContentEncoding("utf-8");
        String uploadPath = null;

        try {
            // 上传文件到存储桶
            // 文件后缀名
            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 文件上传路径 /driver/path/uuid.jpg，避免文件名重复导致被覆盖
            uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
            // 构建上传文件请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(), uploadPath, file.getInputStream(), metadata);
            putObjectRequest.setStorageClass(StorageClass.Standard);
            // 执行上传
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            log.info("上传结果：{}", JSON.toJSONString(putObjectResult));

            // 审核上传图片
            Boolean result = ciService.imageAuditing(uploadPath);
            if (!result) {
                // 图片审核不通过，删除上传图片，提示司机重新上传
                cosClient.deleteObject(tencentCloudProperties.getBucketPrivate(), uploadPath);
                throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.FAIL);
        } finally {
            // 关闭客户端
            cosClient.shutdown();
        }

        // 封装返回结果
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        // 图片临时访问 URL，回显使用
        cosUploadVo.setShowUrl(this.getTempImageUrl(uploadPath));

        return cosUploadVo;
    }

    /**
     * 获取图片临时 URL 用于回显
     * @param path
     * @return
     */
    @Override
    public String getTempImageUrl(String path) {
        if (!StringUtils.hasText(path)) {
            return "";
        }
        COSClient cosClient = this.getPrivateCOSClient();
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);
        // 设置图片临时访问 URL 有效期为 15 分钟
        Date expiration = new DateTime().plusMinutes(15).toDate();
        urlRequest.setExpiration(expiration);
        URL url = cosClient.generatePresignedUrl(urlRequest);
        cosClient.shutdown();
        return url.toString();
    }
}
